package leetcode100;


public class lc005 {
    static class LinkedList {
        ListNode head;

        LinkedList add(int value) {
            ListNode node = new ListNode(value);
            if (this.head == null) {
                this.head = node;
                return this;
            }

            ListNode cur = this.head;
            while (cur.next != null) {
                cur = cur.next;
            }
            cur.next = node;
            return this;
        }

        void visit() {
            ListNode node = this.head;
            while (node != null) {
                System.out.print(node.val + " ");
                node = node.next;
            }
            System.out.println();
        }

    }


    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.add(1).add(0).add(0);
        list.visit();
        boolean res = isPalindrome(list.head);
        System.out.println(res);
    }

    public static ListNode reverse(ListNode head) {
        if (head == null) return null;
        if (head.next == null) return head;


        ListNode cur = head;
        ListNode pre = null;
        ListNode next = null;
        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    public static boolean isPalindrome(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        /*
        1 2 3 2 1
            s   f
         1 2 2 1
           s f
         */
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        System.out.println("slow:"+slow.val+" fast:"+fast.val);
        ListNode secondHalf = reverse(slow.next);
        ListNode firstHalf = head;

        while (secondHalf != null) {
            if (firstHalf.val != secondHalf.val) return false;
            firstHalf = firstHalf.next;
            secondHalf = secondHalf.next;
        }


        return true;
    }


}
